package com.tianquan.DistributedLock.Task;/**
 * @author starsea
 * @date 2024-09-26 下午3:20
 */

import com.tianquan.DistributedLock.entiy.Lock;
import com.tianquan.mapper.LockMapper;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.tianquan.DistributedLock.DataBaseLock.get30SecondsTimestamp;
import static com.tianquan.DistributedLock.DataBaseLock.getTimestampOfDateTime;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.DistributedLock
 * @Author: tianquan
 * @CreateTime: 2024-09-26  15:20
 * @Description: 锁定时刷新
 * @Version: 1.0
 */

// @Component
public class LockRenewalTask {

    public static final Map<String, Lock> LOCAL_MAP = new ConcurrentHashMap<>(64);

    // @Autowired
    private LockMapper lockMapper;

    // 定时任务，每隔一段时间执行一次锁续约的逻辑,时间1秒
    @Scheduled(cron = "0/1 * * * * ?")
    public void renewalTask() {
        System.out.println("-----------定时任务执行了----------");
        // 获取到所有需要续期的锁
        Map<String, Lock> map = new HashMap<>(LOCAL_MAP);
        map.forEach((s, lock) -> {
            // 锁的过期时间戳
            Long expirationTime = lock.getExpirationTime();
            // 当前时间戳
            Long timestampOfDateTime = getTimestampOfDateTime(LocalDateTime.now());
            // 判断是否需要续期，有效时间不足或等于20秒就需要续期
            long time = expirationTime - timestampOfDateTime;
            if (time <= 20000) {
                // 续期
                lock.setExpirationTime(get30SecondsTimestamp());
                lockMapper.renewal(lock);
                System.out.println("续期成功");
            }
        });
        System.out.println("-----------定时任务结束了----------");
    }

}
